#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>


#define SIZE 1024
#define MAX_ARGC 64
#define SEP " "

char *argv[MAX_ARGC];

const char* HostName()
{
    char *hostname = getenv("HOSTNAME");
    if(hostname) return hostname;
    else return "None";
}

const char* UserName()
{
    char *hostname = getenv("USER");
    if(hostname) return hostname;
    else return "None";
}

const char *CurrentWorkDir()
{
    char *hostname = getenv("PWD");
    if(hostname) return hostname;
    else return "None";
}

const char* Home()
{
    return getenv("HOME")
}

int Interactive(char out[],int size)
{
    //输出提示符并获取用户输入的命令字符串”ls -a -l“
    printf("[%s@%s %s]",UserName(),HostName(),CurrentWorkDir());
    fgets(out,size,stdin);
    out[(strlen(out))-1] = 0;//使其没有\n

    return strlen(out);//commandline是否为空串。
}

void Split(char in[])
{
    int i = 0;
    argv[i++] = strtok(in,SEP);
    while(argv[i++] = strtok(NULL,SEP));
}

void Execute()
{
    
    pid_t id = fork();
    if(id == 0)
    {
        //让子进程执行命令
        execvp(argv[0],argv);
        exit(1);
    }
    pid_t rid = waitpid(id,NULL,0);
    printf("run done,rid:%d\n",rid);
}

int BuildinCmd()
{

}


int main()
{   
    while(1)
    {
         //1。打印命令行提示符，获取用户输入的命令行字符串
         char commandline[SIZE];
         int n = Interactive(commandline,SIZE);
         if(n == 0) continue;
         //2.对命令行字符串进行切割
         Split(commandline); 
         
        //3.处理内建命令
         n =  BuildinCmd();
         if(n) continue;

         //4.执行命令
         Execute();
    }
    return 0;

}
